package com.itheima.test002;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Test001 {
    /*
    有一个String[]数组如下：

    String[] nums = {“3.22”,”8.1”,”7”,”2.5”,”3.1”,”7.77”,”8.0”,”9.21”};

    请编程计算它们的平均值，结果精确到小数点后两位。
     */
    public static void main(String[] args) {
        String[] nums = {"3.22","8.1","7","2.5","3.1","7.77","8.0","9.21"};
        //创建一个sum变量;
        //创建一个sum对象;
        BigDecimal sum= new BigDecimal("0");
        //遍历集合;让每一个元素相加;
        for (int i = 0; i < nums.length; i++) {
            sum= sum.add(new BigDecimal(nums[i]+""));
        }
        System.out.println("相加之和为:"+sum);
        System.out.println("平均值为:"+sum.divide(new BigDecimal(nums.length),2,RoundingMode.HALF_UP));


    }

    private static void method02(String[] nums) {
        BigDecimal sum =  new BigDecimal("0");
        for (int i = 0; i < nums.length; i++) {
            sum= sum.add(new BigDecimal(nums[i]+""));
        }
        System.out.println(sum.divide(new BigDecimal(nums.length),2, RoundingMode.HALF_UP));
    }

    private static void method(String[] nums) {
        BigDecimal sum = new BigDecimal("0");
        for (int i = 0; i < nums.length; i++) {
            //BigDecimal bg1= new BigDecimal(nums[i]+"");
            //bg= bg.add(bg1);
            sum = sum.add(new BigDecimal(nums[i]+""));
        }
        BigDecimal avg = sum.divide(new BigDecimal(nums.length),2, RoundingMode.HALF_UP);
        System.out.println(avg);
    }
}
